#!/usr/bin/python3
#coding=utf-8

#todo
# must first check the /etc/X11/Xsession and other script is exist or not


import os
import getpass

#need to init
# 0. add current user(sk) to sudoers, and set not need password when use sudo:
#    modify /etc/sudoers in root :
#         chmod +w /etc/sudoers
#         add :
#                 sk ALL=(ALL) NOPASSWD:ALL
#         or admin group not need password: ??
#                 %admin ALL=(ALL) NOPASSWD:ALL
#         chmod -w /etc/sudoers
# 1. PATH/PS1/alias
# 2. keymap
# 3. emacs profile / all code & script in svn repo
# 4. sys init script (emacs daemon, proxy)
# 5. env of sys (shortcuts:steward)
# 6. stop touchpad
# 7. xterm & tmux
# 8. font:
##terminus是我喜欢的一款终端字体，你可以通过#cd /usr/ports/x11-fonts/terminus-font && make install clean 来安装。WenQuanYi Bitmap Song则是一款点阵中文字体，#cd /usr/ports/x11-fonts/wqy && make install clean (ps:个人偏好点阵)。所有的字体名字都可以通过命令fc-list得到，选择你喜欢的就是了。不过注意，终端一定要用等宽字体，名字里面带Mono的就是。
# 9. launch steward under X
#print("setting keymap ......")

scriptFile = None
lines = None
homepath = os.path.expanduser('~')
username = getpass.getuser()


def loadScript(filename):
    global scriptFile, lines
    scriptFile = filename
    lines = open(scriptFile, "r").readlines()
    for i in range(len(lines)):
        lines[i] = lines[i].rstrip()    #strip the space or '\n'
    for i in range(len(lines)-1, -1, -1):
        if lines[i] == '':
            del lines[i]                #del the blank line from end

#key is like "PATH" or "export PATH"
def getValueFromScript(key):
    global lines
    key = key + "="
    result = None
    length = len(key)
    for line in lines:
        if len(line)>=length and line[0:length] == key:
            result = line[length:]  #may assign more than once, only the last valid
    return result       #if not find, return None (diff from '')
            
def setVarToScript(key, value):
    global lines
    #first del the already exist var
    if value != None:
        key += "="
    length = len(key)
    i = 0
    maxLen = len(lines)
    while i < maxLen:
        if len(lines[i])>=length and lines[i][0:length] == key :
            del lines[i]
            maxLen = maxLen - 1
        else:
            i = i + 1
    #add the var to the end
    if value == None:
        lines.append(key)
    else:
        lines.append(key+value)
    
def saveScript():
    global scriptFile
    if scriptFile == None:
        print("Error ! Not load script file !")
    f = open(scriptFile, "w")
    for line in lines:
        f.write(line+"\n")
    f.close()
    scriptFile = None

    



#def setEnvInScript(key, value):
#    getValueFromScript(key)
    
#def getValueFromScript(filename, key):
#def setEnvInScript(filename, key, value):
#    lines = open(filename, "r").readlines()
    

def    getMutexSelection(prompt, default):
    if default == 'y':
        prompt += " y/n "
    else:
        prompt += " n/y "
        default = 'n'
        
    while True:
        key = input(prompt).lower()
        if key == '':   #just press enter
            key = default
        if key == 'y':
            print("appling ...")
            return "y"
        elif key == 'n':
            print("not apply")
            return "n"
        else:
            print("please input 'y' or 'n' ")

def getRootPriv():
    print("get root ...")

        
def set_Emacs():
    global homepath
    ret = 0
    print("setting .emacs & .emacs.d ...(1/3)")
    #################  setting .emacs ###################
    if os.path.exists(homepath+"/.emacs") and os.path.islink(homepath+"/.emacs")==False:
        print("'.emacs' exist and not a symbol link, backup it to ~/emacs.bak")
        os.system("mv %s/.emacs %s/emacs.bak" % (homepath, homepath))
    #make .emacs refer to emacs.conf.el 
    ret |= os.system("ln -sf %s/sk-chang/syncemacs/emacsprofile/emacs.conf.el %s/.emacs" % (homepath, homepath))
    #################  setting .emacs.d ###################
    if os.path.exists(homepath+"/.emacs.d") and os.path.islink(homepath+"/.emacs.d")==False:
        print("'.emacs.d' exist and not a symbol link, backup it to ~/emacs.d.bak")
        os.system("mv %s/.emacs.d %s/emacs.d.bak" % (homepath, homepath))
    else:
        os.system("rm -f %s/.emacs.d" % homepath)
    ret |= os.system("ln -sf %s/sk-chang/syncemacs/emacsprofile/emacs.d %s/.emacs.d" % (homepath, homepath))


    print("setting run script ...(2/3)")
    print("Please select y for set_AutorunScript()")
    
    print("setting ec/et alias ...(3/3)")
    loadScript(homepath+"/.bashrc")
    setVarToScript("alias ec", "'emacsclient -c'")
    setVarToScript("alias et", "'emacsclient -t'")
    saveScript()

    return ret


def set_Keymap():
    global homepath
    print("set Keymap in terminal and X")
    print("Menu -> Right Ctrl")
    ret = 0
    #keymap in terminal
    #add to /etc/rc.local
    #loadkeys /home/sk/sk-chang/config/key.map.gz
    runCmd = ('loadkeys %s/sk-chang/config/key.map.gz' % homepath).replace('/', '\\/').replace('"', '\\"')
    print(runCmd)
    ret |= os.system("sudo sed -i '/%s/d;/exit 0/i\%s' /etc/rc.local" % (runCmd, runCmd))
    if ret==0:
        print("take affect right now")
        os.system("sudo loadkeys %s/sk-chang/config/key.map.gz" % homepath)
    
    #keymap under X, add to /etc/X11/Xsession
    #xmodmap -e "keysym Menu = Control_R"
    #xmodmap -e "add control = Control_R"
    print("set keymap in X (to /etc/X11/Xsession)")
    runCmd = 'xmodmap -e "keysym Menu = Control_R"'.replace('/', '\\/').replace('"', '\\"')
    ret |= os.system("sudo sed -i '/%s/d;/exit 0/i\%s' /etc/X11/Xsession" % (runCmd, runCmd))
    runCmd = 'xmodmap -e "add control = Control_R"'.replace('/', '\\/').replace('"', '\\"')
    ret |= os.system("sudo sed -i '/%s/d;/exit 0/i\%s' /etc/X11/Xsession" % (runCmd, runCmd))
    if ret == 0:
        print("take affect right now")
        os.system("sudo xmodmap -e 'keysym Menu = Control_R'")
        os.system("sudo xmodmap -e 'add control = Control_R'")
    return ret


def set_Xterm():
    global homepath
    ret = 0
    if os.path.exists(homepath+"/.Xresources") and os.path.islink(homepath+"/.Xresources")==False:
        print("'.Xresources exist and not a symbol link, backup it to ~/Xresources.bak")
        os.system("mv %s/.Xresources %s/Xresources.bak" % (homepath, homepath))
    ret |= os.system("ln -sf %s/sk-chang/config/Xresources %s/.Xresources" % (homepath, homepath))
    #take effect
    ret |= os.system("xrdb %s/.Xresources" % homepath)
    return ret

def set_Tmux():
    global homepath
    ret = 0
    if os.path.exists(homepath+"/.tmux.conf") and os.path.islink(homepath+"/.tmux.conf")==False:
        print("'.tmux.conf exist and not a symbol link, backup it to ~/tmux.conf.bak")
        os.system("mv %s/.tmux.conf %s/tmux.conf.bak" % (homepath, homepath))
    ret |= os.system("ln -sf %s/sk-chang/config/tmux.conf %s/.tmux.conf" % (homepath, homepath))

    loadScript(homepath+"/.bashrc")
    setVarToScript('[[ $TERM != "screen" ]] && tmux && exit', None)
    saveScript()

    return ret



#others (inserted to .bashrc):
# # TMUX
# if which tmux 2>&1 >/dev/null; then
#     # if no session is started, start a new session
#     test -z ${TMUX} && tmux

#     # when quitting tmux, try to attach
#     while test -z ${TMUX}; do
#         tmux attach || break
#     done
# fi


def set_AutorunScript():
    global homepath
    ret = 0
    print("Add ~/sk-chang/config/rc.terminal to /etc/rc.local")
    print("Auto run emacs daemon & goagent proxy only for current user when computer start")
    runCmd = 'su sk -c "/bin/sh %s/sk-chang/config/rc.terminal &"' % homepath
    runCmd = runCmd.replace('/', '\\/').replace('"', '\\"')
    #ret |= os.system("sudo sed -i -e '/%s/d' -e '$a\%s' /etc/rc.local" % (runCmd, runCmd))      #not valid
    #ret |= os.system("sudo sed -i -e '/%s/d' -e '$i\%s' /etc/rc.local" % (runCmd, runCmd))      #there exist 'exit 0'
    ret |= os.system("sudo sed -i '/%s/d;/exit 0/i\%s' /etc/rc.local" % (runCmd, runCmd))
    return ret
    
def set_AutorunUnderX():
    global homepath
    ret = 0
    # /etc/X11/xinit/xinitrc 
    # /etc/X11/Xsession         --- valid for all start method(startx or xdm)
    # ~/.xinitrc
    # ~/.xsession               --- valid for current logged user

    print("Autostart while WM started (for dwm)")
    runCmd = "/bin/sh %s/sk-chang/config/rc.X &" % homepath
    runCmd = runCmd.replace('/', '\\/').replace('"', '\\"')
    #ret |= os.system("sed -i '/%s/d;$ i\%s' %s/.xinitrc" % (runCmd, runCmd, homepath))
    ret |= os.system("sed -i '/%s/d;$ i\%s' %s/sk-chang/config/dwmplus/autostart.sh" % (runCmd, runCmd, homepath))
    return ret

#     print("re-write ~/.xsession")
#     print("autorun steward, ibus, xrdb and disable beep when X started")
#     f = open("%s/.xsession" % homepath, "w")
#     script = '''\
# #!/bin/sh
# # user Xsession file

# xrdb ~/.Xresources
# xset -b
# ibus-daemon --xim -d
# steward &
# '''
#     f.write(script)
#     f.close()
#     return 0



def displayState(ret):
    if ret == 0:
        print("Succeed !")
    else:
        print("failed !")

    
    
if __name__ == '__main__':
    print("software & libs should installed(for ubuntu):")
    print('''
1. mg w3m workrave subversion conky emacs python3
2.for dwm:
libX11-dev libXinerama-dev libXft-dev
3.for tmux:
libevent-dev libbsd-dev
''')
    print()
####################################################################################################
    print("Notice :")
    print("0. This script can be performed reduplicate\nbut you may manually modify corresponding script to cancel the settings if it is alreadyset")
    print("1. /etc/rc.local must end with \"exit 0\", otherwise will not affect this script")
    print("2. must install the (DejaVu Sans) and WenQuanYi Zen Hei fonts, otherwise the xterm will not display chinese")
    print("3. you must add current user to /etc/sudoers, You can do this in root")
    print("(sk is your username, here set no password to use sudo)\n")
    print("chmod +w /etc/sudoers")
    print("add :\n sk ALL=(ALL) NOPASSWD:ALL")
    print("chmod -w /etc/sudoers\n")

####################################################################################################        
    print("Set Some Links")
    print("link /usr/local/bin/steward to ~/sk-chang/pyqt/steward/steward.py")
    os.system("sudo ln -sf %s/sk-chang/pyqt/steward/steward.py /usr/local/bin/steward" % homepath)
####################################################################################################    
    #first load script
    loadScript(homepath+"/.bashrc")

    #second modify 
    #setVarToScript("PATH", "$PATH:/home/sk/gsutil")
    #setVarToScript("TEST", "test")

    #set PS1
    PS1_VAR = r''''`a=$?;if [ $a -ne 0 ]; then a="  "$a; echo -ne "\[\e[s\e[1A\e[$((COLUMNS-2))G\e[33m\e[1;41m${a:(-3)}\e[u\]\[\e[0m\e[7m\e[2m\]"; fi`\[\e[1;32m\]\u@\h:\[\e[0m\e[1;34m\]\W\[\e[1;34m\]\$ \[\e[0m\]'
'''[:-1]
    if getMutexSelection("set PS1 ?", "y") == 'y':
        setVarToScript("PS1", PS1_VAR)

    #last, save !!!
    saveScript()
####################################################################################################    
    if getMutexSelection("set Keymap ?", "n") == 'y':   #default not to set
        ret = set_Keymap()
        displayState(ret)
####################################################################################################    
    if getMutexSelection("set Autorun script ?", "y") == 'y':
        ret = set_AutorunScript()
        displayState(ret)
        if getMutexSelection("take autorun script effect right now ?", "n") == 'y':
            os.system("/bin/sh %s/sk-chang/config/rc.terminal &" % homepath)

    if getMutexSelection("set Autorun under X ?", "y") == 'y':
        ret = set_AutorunUnderX()
        displayState(ret)
        print("you can modify the ~/sk-chang/config/rc.X to change the autostart list !")
        if getMutexSelection("take autorun under X effect right now ?", "n") == 'y':
            os.system("/bin/sh %s/sk-chang/config/rc.X &" % homepath)
####################################################################################################    
    if getMutexSelection("set Xterm ?", "y") == 'y':
        ret = set_Xterm()
        displayState(ret)

    if getMutexSelection("set Tmux ?", "y") == 'y':
        ret = set_Tmux()
        displayState(ret)
        if ret == 0:
            print("please kill tmux process and re-start one to see the effect")

    if getMutexSelection("set Emacs ?", "y") == 'y':
        ret = set_Emacs()
        displayState(ret)
####################################################################################################
    if getMutexSelection("install chsdir(convenient for chinese file or dir) ?", "y") == 'y':
        os.system("cd chsdir;/bin/sh install.sh")
####################################################################################################
        
    print("Other Notice:")
    print("1. for ibus: add corresponding env to /etc/profile")
    print("2. turn off/on touchpad : synclient TouchpadOff=1/0")
    print("3. sync the date : sudo ntpdate pool.ntp.org")
# disable touchpad
# sudo rmmod psmouse
# sudo modprobe psmouse        

# update the time
# sudo ntpdate pool.ntp.org


# #for wine
# 1. mybase
# 2. picpick
# /usr/bin/picpick 
# #!/bin/sh
# wine "/home/sk/.wine/drive_c/Program Files/PicPick/picpick.exe"


# image viewer : feh    
